/*
 * enc_rtc.cpp
 *
 *  Created on: 2019年1月2日
 *  Author: Degang.Wu (windragon@126.com)
 *  Desc:
 */

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <string.h>
#include "hi_rtc.h"

static const char *dev_name = "/dev/hi_rtc";

void hienc_rtc_init()
{
	static int init_flag = 0;
	rtc_time_t t_now;
	rtc_time_t* tm = &t_now;
	if (init_flag)
	{
		return;
	}
	init_flag++;

	int fd = -1;
	if (!tm)
	{
		return;
	}
	fd = open(dev_name, O_RDWR);
	if (fd < 0)
	{
		fprintf(stderr, "open %s failed\n", dev_name);
		return;
	}

	int ret = ioctl(fd, HI_RTC_RD_TIME, tm);
	close(fd);

	if (ret < 0)
	{
		fprintf(stderr, "ioctl: HI_RTC_RD_TIME failed\n");
		return;
	}

	char tmstr[64];
	snprintf(tmstr, sizeof(tmstr), "%04d-%02d-%02d %02d:%02d:%02d", tm->year,
			tm->month, tm->date, tm->hour, tm->minute, tm->second);
	char cmd[1024];
	snprintf(cmd, sizeof(cmd), "date -s \"%s\"", tmstr);
	system(cmd);
}

int hienc_get_rtctime(rtc_time_t* tm)
{
	int fd = -1;
	if (!tm)
	{
		return -1;
	}
	fd = open(dev_name, O_RDWR);
	if (fd < 0)
	{
		fprintf(stderr, "open %s failed\n", dev_name);
		return -1;
	}

	int ret = ioctl(fd, HI_RTC_RD_TIME, tm);
	if (ret < 0)
	{
		fprintf(stderr, "ioctl: HI_RTC_RD_TIME failed\n");
	}

	close(fd);
	return ret;
}

int hienc_set_time(rtc_time_t* tm)
{
	int fd = -1;
	if (!tm)
	{
		return -1;
	}
	fd = open(dev_name, O_RDWR);
	if (fd < 0)
	{
		fprintf(stderr, "open %s failed\n", dev_name);
		return -1;
	}
	int ret = ioctl(fd, HI_RTC_SET_TIME, tm);

	if (ret < 0)
	{
		fprintf(stderr, "ioctl: HI_RTC_SET_TIME failed\n");
		close(fd);
		return -1;
	}

	close(fd);

	// set system time
	char tmstr[64];
	snprintf(tmstr, sizeof(tmstr), "%04d-%02d-%02d %02d:%02d:%02d", tm->year,
			tm->month, tm->date, tm->hour, tm->minute, tm->second);
	char cmd[1024];
	snprintf(cmd, sizeof(cmd), "date -s \"%s\"  >/dev/null", tmstr);
//	fprintf(stderr, "set rtc time:%s\n", cmd);
	system(cmd);

	fflush(stderr);
	return 0;
}

void dump_current_time()
{
	rtc_time_t t_now;
	memset(&t_now, 0, sizeof(t_now));
	rtc_time_t * tm = &t_now;
	if (0 == hienc_get_rtctime(&t_now))
	{
		fprintf(stdout, "%04d-%02d-%02d %02d:%02d:%02d\n", tm->year,
				tm->month, tm->date, tm->hour, tm->minute, tm->second);
	}
}
